<template>
    <div class="infor-manage">
        <div class="infor-manage__header">
            <div class="infor-manage__header__title">
                <span>信息管理</span>
            </div>

            <!-- 标签页切换 -->
            <div class="infor-manage__header__tabs">
                <el-tabs v-model="activeTab" @tab-change="handleTabChange">
                    <el-tab-pane label="最新医疗新闻" name="news"></el-tab-pane>
                    <el-tab-pane label="健康科普文章" name="article"></el-tab-pane>
                    <el-tab-pane label="特色医疗技术" name="technology"></el-tab-pane>
                </el-tabs>
            </div>
        </div>

        <div class="infor-manage__content" v-loading="false" element-loading-text="加载中...">
            <!-- 操作按钮区 -->
            <div class="infor-manage__content__actions">
                <el-button type="primary" @click="handleAdd">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    新增
                </el-button>
            </div>

            <!-- 错误提示 -->
            <el-alert v-if="error" :message="error" type="error" show-icon closable @close="clearError"></el-alert>

            <!-- 数据表格容器 -->
            <div v-else-if="sortedDataList.length > 0" class="table-container">
                <el-table :data="sortedDataList" border style="width: 100%; margin-top: 16px;">
                    <el-table-column 
                        :prop="currentModuleConfig.listFieldMap.title" 
                        label="标题" 
                        width="800"
                    ></el-table-column>
                    <el-table-column 
                        :prop="currentModuleConfig.listFieldMap.publishTime" 
                        label="发布时间" 
                        width="330"
                    ></el-table-column>
                    <el-table-column label="操作" width="223">
                        <template #default="scope">
                            <el-button 
                                type="primary" 
                                size="small" 
                                @click="handleEdit(scope.row)" 
                                style="margin-right: 5px"
                            >
                                编辑
                            </el-button>
                            <el-button 
                                type="danger" 
                                size="small" 
                                @click="handleDelete(scope.row[currentModuleConfig.idField])"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 空状态 -->
            <div v-else class="infor-manage__content__empty">
                <el-empty description="暂无数据"></el-empty>
            </div>
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog 
            v-model="dialogVisible" 
            :title="dialogTitle" 
            width="800px"
            @close="handleDialogClose"
        >
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" class="custom-form">
                <el-form-item label="标题" :prop="currentModuleConfig.formFieldMap.title" >
                    <el-input 
                        v-model="formData[currentModuleConfig.formFieldMap.title]" 
                        placeholder="请输入标题"
                    ></el-input>
                </el-form-item>
                <el-form-item label="内容" :prop="currentModuleConfig.formFieldMap.content">
                    <el-input 
                        v-model="formData[currentModuleConfig.formFieldMap.content]" 
                        type="textarea" 
                        rows="5" 
                        placeholder="请输入内容"
                    ></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="handleDialogClose">取消</el-button>
                <el-button type="primary" @click="handleSave">保存</el-button>
            </template>
        </el-dialog>

        <!-- 删除确认对话框 -->
        <el-dialog v-model="deleteDialogVisible" title="确认删除" width="300px">
            <p>确定要删除这条数据吗？此操作不可撤销。</p>
            <template #footer>
                <el-button @click="deleteDialogVisible = false">取消</el-button>
                <el-button type="danger" @click="confirmDelete">确认删除</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, reactive } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { useInforNewsStore } from '@/stores/information/news';
import { useInforArticleStore } from '@/stores/information/article';
import { useInforTechStore } from '@/stores/information/technology';
import { ElMessage, ElForm } from 'element-plus';


// 标签页状态管理
const activeTab = ref('news');

// 对话框状态
const dialogVisible = ref(false);
const dialogTitle = ref('新增');
const deleteDialogVisible = ref(false);
const currentId = ref<number | string | null>(null);

// 表单数据（动态适配不同模块的字段）
const formData = reactive<Record<string, any>>({});

// 引入stores
const newsStore = useInforNewsStore();
const articleStore = useInforArticleStore();
const techStore = useInforTechStore();

// 核心：模块配置映射表（统一管理不同模块的差异）
const moduleConfigs = {
  news: {
    fetchData: () => newsStore.getAllNews(),
    fetchDetail: (id: number) => newsStore.getNewsById(id),
    addData: (data: any) => newsStore.addNews(data),
    editData: (data: any) => newsStore.editNews(data),
    deleteData: (id: number) => newsStore.removeNews(id),
    idField: 'newsId',
    listFieldMap: {
      title: 'newsTitle',
      publishTime: 'publishTime'
    },
    formFieldMap: {
      title: 'newsTitle',
      content: 'newsContent',
      status: 'status'
    },
    formRules: {
      newsTitle: [
        { required: true, message: '请输入新闻标题', trigger: 'blur' },
        { max: 100, message: '标题长度不能超过100个字符', trigger: 'blur' }
      ],
      newsContent: [
        { required: true, message: '请输入新闻内容', trigger: 'blur' }
      ]
    }
  },
  article: {
    fetchData: () => articleStore.getAllArticles(),
    fetchDetail: (id: string) => articleStore.getArticleById(id),
    addData: (data: any) => articleStore.addArticle(data),
    editData: (data: any) => articleStore.editArticle(data),
    deleteData: (id: string) => articleStore.removeArticle(id),
    idField: 'articleId',
    listFieldMap: {
      title: 'articleTitle',
      publishTime: 'publishTime'
    },
    formFieldMap: {
      title: 'articleTitle',
      content: 'articleContent',
      status: 'status'
    },
    formRules: {
      articleTitle: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
        { max: 100, message: '标题长度不能超过100个字符', trigger: 'blur' }
      ],
      articleContent: [
        { required: true, message: '请输入文章内容', trigger: 'blur' }
      ]
    }
  },
  technology: {
    fetchData: () => techStore.getAllTech(),
    fetchDetail: (id: string) => techStore.getTechById(id),
    addData: (data: any) => techStore.addTech(data),
    editData: (data: any) => techStore.editTech(data),
    deleteData: (id: string) => techStore.removeTech(id),
    idField: 'techId',
    listFieldMap: {
      title: 'techTitle',
      publishTime: 'publishTime'
    },
    formFieldMap: {
      title: 'techTitle',
      content: 'techContent',
      status: 'status'
    },
    formRules: {
      techTitle: [
        { required: true, message: '请输入技术名称', trigger: 'blur' },
        { max: 100, message: '名称长度不能超过100个字符', trigger: 'blur' }
      ],
      techContent: [
        { required: true, message: '请输入技术描述', trigger: 'blur' }
      ]
    }
  }
};

// 获取当前模块的配置
const currentModuleConfig = computed(() => {
  return moduleConfigs[activeTab.value as keyof typeof moduleConfigs] || moduleConfigs.news;
});

// 表单验证规则（动态适配当前模块）
const formRules = computed(() => currentModuleConfig.value.formRules);

// 当前模块的数据列表
const dataList = computed(() => {
  switch (activeTab.value) {
    case 'news':
      return newsStore.newsList;
    case 'article':
      return articleStore.articles;
    case 'technology':
      return techStore.techList;
    default:
      return [];
  }
});

// 排序后的数据列表 - 按发布时间从新到旧排序
const sortedDataList = computed(() => {
  const publishTimeField = currentModuleConfig.value.listFieldMap.publishTime;
  return [...dataList.value].sort((a, b) => {
    const timeA = new Date(a[publishTimeField]).getTime();
    const timeB = new Date(b[publishTimeField]).getTime();
    return timeB - timeA;
  });
});

// 错误信息
const error = computed(() => {
  const store = getCurrentStore();
  return store.error;
});

// 获取当前模块对应的store
const getCurrentStore = () => {
  switch (activeTab.value) {
    case 'news':
      return newsStore;
    case 'article':
      return articleStore;
    case 'technology':
      return techStore;
    default:
      return newsStore;
  }
};

// 清除错误信息
const clearError = () => {
  getCurrentStore().error = null;
};

// 初始化数据方法
const initData = async () => {
  try {
    await currentModuleConfig.value.fetchData();
  } catch (err) {
    console.error(`初始化${activeTab.value}数据失败:`, err);
    ElMessage.error(`加载${getModuleName()}数据失败`);
  }
};

// 获取模块中文名称
const getModuleName = () => {
  const moduleNames = {
    news: '最新医疗新闻',
    article: '健康科普文章',
    technology: '特色医疗技术'
  };
  return moduleNames[activeTab.value as keyof typeof moduleNames] || '数据';
};

// 页面加载时初始化数据
onMounted(() => {
  initData();
});

// 标签页切换时重新加载数据
const handleTabChange = () => {
  Object.keys(formData).forEach(key => delete formData[key]);
  initData();
};

// 新增操作
const handleAdd = () => {
  dialogTitle.value = `新增${getModuleName()}`;
  currentId.value = null;
  
  const fields = currentModuleConfig.value.formFieldMap;
  Object.assign(formData, {
    [fields.title]: '',
    [fields.content]: '',
  });
  
  if (formRef.value) {
    formRef.value.clearValidate();
  }
  dialogVisible.value = true;
};

// 编辑操作
const handleEdit = async (row: any) => {
  try {
    dialogTitle.value = `编辑${getModuleName()}`;
    const idField = currentModuleConfig.value.idField;
    currentId.value = row[idField];
    
    const detail = await currentModuleConfig.value.fetchDetail(row[idField]);
    
    if (detail) {
      const fields = currentModuleConfig.value.formFieldMap;
      Object.assign(formData, {
        [fields.title]: detail[fields.title] || '',
        [fields.content]: detail[fields.content] || '',
      });
      dialogVisible.value = true;
    }
  } catch (err) {
    console.error(`获取${getModuleName()}详情失败:`, err);
    ElMessage.error(`获取${getModuleName()}详情失败`);
  }
};

// 保存操作
const handleSave = async () => {
  if (!formRef.value) return;
  const valid = await formRef.value.validate();
  if (!valid) return;

  try {
    const fields = currentModuleConfig.value.formFieldMap;
    const submitData = {
      [fields.title]: formData[fields.title],
      [fields.content]: formData[fields.content],
    };

    if (currentId.value === null) {
      await currentModuleConfig.value.addData(submitData);
      ElMessage.success(`新增${getModuleName()}成功`);
    } else {
      await currentModuleConfig.value.editData({
        [currentModuleConfig.value.idField]: currentId.value,
        ...submitData
      });
      ElMessage.success(`编辑${getModuleName()}成功`);
    }

    dialogVisible.value = false;
    initData();
  } catch (err) {
    console.error(`${currentId.value === null ? '新增' : '编辑'}${getModuleName()}失败:`, err);
    ElMessage.error(`${currentId.value === null ? '新增' : '编辑'}${getModuleName()}失败`);
  }
};

// 处理删除
const handleDelete = (id: string) => {
  currentId.value = id;
  deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  if (!currentId.value) return;

  try {
    await currentModuleConfig.value.deleteData(currentId.value);
    ElMessage.success(`删除${getModuleName()}成功`);
    deleteDialogVisible.value = false;
    initData();
  } catch (err) {
    console.error(`删除${getModuleName()}失败:`, err);
    ElMessage.error(`删除${getModuleName()}失败`);
  }
};

// 对话框关闭时的处理
const handleDialogClose = () => {
  dialogVisible.value = false;
};

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>();
</script>

<style lang="scss" scoped>
.infor-manage {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 64px);

    &__header {
        margin-bottom: 20px;

        &__title {
            font-size: 20px;
            font-weight: 600;
            color: #1f2329;
            margin-bottom: 16px;
        }
    }

    &__content {
        background-color: #fff;
        padding: 20px;
        border-radius: 4px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        width: 100%;
        box-sizing: border-box;

        &__actions {
            margin-bottom: 16px;
        }

        &__empty {
            padding: 40px 0;
            text-align: center;
        }
    }
    
    .table-container {
        width: 100%;
        flex: 1;
        display: flex;
        flex-direction: column;
    }
    
    .custom-form {
      .el-input,
      .el-select {
        width: 100%;
      }
    }
}
</style>